<template>
  <div class="breadcrumb">
    <!-- 导航栏部分 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <!-- 默认样式紧挨着，这里的el-breadcrumb设置在全局样式文件 global.css中 -->
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片主体区域 -->
    <el-card class="box-card">
      <el-row class="mianbaoxie">
        <el-col>
          <el-button type="primary" @click="getAddCate()">添加分类</el-button>
        </el-col>
      </el-row>
      <!-- 信息展示部分 :expand-type：是否开启拓展 selection-type：是否开启多选
        show-index index-text="#"：显示序号并且序号列名用#显示-->
      <tree-table
        :data="cateList"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        show-index
        index-text="#"
        border
        :show-row-hover="false"
      >
        <template slot="isok" slot-scope="scope">
          <i
            class="el-icon-success"
            v-if="(scope.cat_delete = 'false')"
            style="color: lightgreen"
          ></i>
          <i class="el-icon-error" v-else style="color: red"></i>
        </template>
        <template slot="order" slot-scope="scope">
          <el-tag v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag type="success" v-if="scope.row.cat_level === 1">二级</el-tag>
          <el-tag type="warning" v-if="scope.row.cat_level === 2">三级</el-tag>
        </template>
        <template slot="opt" slot-scope="scope">
          <el-button type="primary" size="mini" icon="el-icon-edit"
            >编辑</el-button
          >
          <el-button type="danger" size="mini" icon="el-icon-delete"
            >删除</el-button
          >
        </template>
      </tree-table>
      <!-- 分页部分 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="cateParam.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="cateParam.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>

      <!-- 添加分类的消息框 -->
      <!-- close：dialog表单关闭事件 -->
      <el-dialog
        title="添加分类"
        :visible.sync="addDialogVisible"
        width="40%"
        :before-close="beforeClose"
        @close="addDialogClosed"
      >
        <!-- ref：表单提交的对象名   rules：数据规则     model：数据对象，用于保存以便其他功能方法使用 -->
        <el-form
          :model="addCateForm"
          :rules="cateRules"
          ref="addCateFormRef"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="分类名称" prop="cat_name">
            <el-input v-model="addCateForm.cat_name"></el-input>
          </el-form-item>
          <el-form-item label="父级分类" prop="cat_pid">
              <!-- option指定数据源 -->
              <!-- prop指定配置对象 -->
              <!-- clearable：增加清除功能 -->
            <el-cascader
              clearable
              v-model="addCateIds"
              :options="secondCateList"
              :props="addProps"
              @change="handleChange"
            ></el-cascader>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="commitAddCate()"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      cateParam: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      total: 0,
      cateList: [],
      columns: [
        {
          label: "分类名称",
          prop: "cat_name",
        },
        {
          label: "是否有效",
          // 将当前列定义为模板列
          type: "template",
          // 模板名称
          template: "isok",
        },
        {
          label: "排序",
          // 将当前列定义为模板列
          type: "template",
          // 模板名称
          template: "order",
        },
        {
          label: "操作",
          // 将当前列定义为模板列
          type: "template",
          // 模板名称
          template: "opt",
        },
      ],
      addDialogVisible: false,
      // 提交参数
      addCateForm: {
        cat_name: "",
        cat_pid: 0,
        cat_level: 0,
      },
      // 添加功能中读取的所有二级分类集合
      secondCateList: [],
      // 添加功能级联选择器的配置参数
      addProps:{
          value: 'cat_id',
          label: 'cat_name',
          children: 'children',
          // 鼠标放上去就展开，默认需要鼠标点击
          expandTrigger: 'hover',
          // 可以选择父分类，默认只能选择叶子结点
          checkStrictly: 'true'
      },
      addCateIds: [],
      cateRules: {
        cat_name: [
          { required: true, message: "请输入分类名", trigger: "blur" },
          {
            min: 3,
            max: 5,
            message: "长度在 3 到 5 个字符",
            trigger: "change",
          },
        ],
        
      }
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get(`categories`, {
        params: this.cateParam,
      });
      if (res.meta.status != 200) {
        this.$http.message.error("分类获取失败!");
      }
      console.log(res.data);
      this.total = res.data.total;
      this.cateList = res.data.result;
    },
    // 改变页码
    handleSizeChange(newSize) {
      this.cateParam.pagesize = newSize;
      this.getCateList();
    },
    // 改变页数
    handleCurrentChange(newPage) {
      this.cateParam.pagenum = newPage;
      this.getCateList();
    },
    //关闭新增、编辑用户dialog框的提示方法
    beforeClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    // 添加分类功能查询分类
    async getSecondCate() {
      const { data: res } = await this.$http.get(`categories`, {
        params: { type: 2 },
      });
      if (res.meta.status != 200) {
        this.$http.message.error("分类获取失败!");
      }
      this.secondCateList = res.data;
      console.log(res.data)
    },
    // 点击添加分类按钮触发
    getAddCate(){
        this.getSecondCate();
        this.addDialogVisible = true;
    },
    // 级联选择器修改时触发
    handleChange(){
        if(this.addCateIds.length>0){
            this.addCateForm.cat_pid = this.addCateIds[this.addCateIds.length-1];
            this.addCateForm.cat_level = this.addCateIds.length;
        }else{

        }
        console.log(this.addCateForm)
    },
    // 添加分类框关闭事件
    addDialogClosed(){
        this.$refs.addCateFormRef.resetFields();
        this.addCateIds = [];
        this.addCateForm.cat_name = '';
        this.addCateForm.cat_pid = 0,
        this.addCateForm.cat_level = 0
    },
    // 提交添加分类
    commitAddCate(){
      this.$refs.addCateFormRef.validate(async (valid) => {
        if (!valid) return;
        console.log(this.addCateForm)
        const { data: res } = await this.$http.post("categories", this.addCateForm);
        if (res.meta.status !== 201)
          return this.$message.error("分类添加失败！");
        this.$message.success("分类添加成功!");
        this.addDialogVisible = false; 
        this.getCateList();
      });
    }
  },
};
</script>

<style scoped lang="less">
</style>
